/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package databook.util;

//import databook.filter.DataFilter;
import databook.controller.Props;

import java.util.HashMap;
import java.util.Iterator;

/**
 *
 * @author zach
 */
public class CountingHash extends CustomHash {

    public CountingHash() {
        super();
    }
    
    public CountingHash(String key, String val, int num) {
        this(key + DELIM + val,num);
    }
    
    public CountingHash(String key, int val) {
        super();
        put(key,new Integer(val));
    }
    
    public Object put(String key, Object val) {
        if (val instanceof Integer) 
            return put(key,((Integer)val).intValue());
        else
            return super.put(key,val);
    }
    
    public Object put(String key, int val) {
        if (containsKey(key)) {
            val = ((Integer)get(key)).intValue() + val;
        }
        return super.put(key,new Integer(val));
    }
    
    public void putAll(HashMap map) {
        Iterator iter = map.keySet().iterator();
        while(iter.hasNext()) {
            String key = (String)iter.next();
            put(key,map.get(key));
        }
    }
    
    public int getInt(String key, String val) {
        return getInt(key + DELIM + val);
    }
    
    public int getInt(String key) {
        return ((Integer)get(key)).intValue();
    }
    
    public int getMax(String prefix) {
        return getMax(prefix,false);
    }
    
    public int getMax(String prefix, boolean filter) {
        Iterator iter = keySet().iterator();
        int max = 0;
        while(iter.hasNext()) {
            String key = (String)iter.next();
            //System.out.println(key + " => " + getInt(key));
            int pos = key.indexOf(DELIM);
            if (key.startsWith(prefix)) {
                if (!filter || Props.filter(key.substring(0,pos),key.substring(pos+DELIM.length()))) {
                    if (getInt(key) > max)
                        max = getInt(key);
                    //System.out.println(key + " => " + getInt(key));
                }
            }
        }
        return max;
    }
    
    public int getMin(String prefix) {
        return getMin(prefix,false);
    }
    
    public int getMin(String prefix, boolean filter) {
        Iterator iter = keySet().iterator();
        int min = -1;
        while(iter.hasNext()) {
            String key = (String)iter.next();
            //System.out.println(key + " => " + getInt(key));
            int pos = key.indexOf(DELIM);
            if (key.startsWith(prefix)) {
                if (!filter || Props.filter(key.substring(0,pos),key.substring(pos+DELIM.length()))) {
                    if (getInt(key) < min || min == -1)
                        min = getInt(key);
                    //System.out.println(key + " => " + getInt(key));
                }
            }
        }
        return min;
    }
    
}
